package com.hltx.controller.login;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hltx.controller.base.BaseController;
import com.hltx.pojo.common.Page;
import com.hltx.pojo.smscode.SmsCodeValidate;
import com.hltx.pojo.user.User;
import com.hltx.pojo.user.UserLogin;
import com.hltx.service.order.OrderManager;
import com.hltx.service.smscode.impl.SmsCodeValidateService;
import com.hltx.service.user.UserManager;
import com.hltx.service.user.UserVipManager;
import com.hltx.util.CustomUtil;
import com.hltx.util.DateUtil;
import com.hltx.util.MD5Util;
import com.hltx.util.MessagesCode;
import com.hltx.util.RegexUtils;
import com.hltx.util.ResultInfo;
import com.hltx.util.sms.code.NeteaseSms;

@Controller
@RequestMapping(value = "/friend/")
public class FriendoginController extends BaseController {

	@Resource(name = "userService")
	private UserManager userService;
	
	@Resource(name="orderService")
	private OrderManager orderService;
	
	@Value("${domain}")
	private String domain;

	@Autowired
	private UserVipManager userVipService;

	@Resource(name = "smsCodeValidateService")
	private SmsCodeValidateService smsCodeValidateService;

	@RequestMapping(value = "outLogin")
	public ModelAndView outLogin(HttpServletResponse response, HttpServletRequest request) {
		ModelAndView view = this.getModelAndView();
		request.getSession().removeAttribute("sessionUser");
		view.setViewName("redirect:/toLogin");
		return view;
	}
	
	@RequestMapping(value = "toRegister")
	public ModelAndView toRegister(HttpServletRequest request) throws Exception {
		ModelAndView view = this.getModelAndView();
		String param = request.getQueryString();
			if (param != null && !"".equals(param)) {
				if (param.indexOf("code")>=0) {
					if(param.length() >= 13){
						String id = param.substring(9, param.length() - 3);
						String phone = userService.getPhone(id);
						view.addObject("phone", phone);
					}
				}
			}
		
		view.setViewName("user/registerFriend");
		return view;
	}
	@RequestMapping(value = "toR")
	public ModelAndView toR(HttpServletRequest request) throws Exception {
		ModelAndView view = this.getModelAndView();
		view.setViewName("user/guide");
		return view;
	}
	
	@RequestMapping(value = "toRS")
	public ModelAndView toRS(HttpServletRequest request,HttpSession session,Page page ) throws Exception {
		ModelAndView view = this.getModelAndView();
		User u = (User) session.getAttribute("sessionUser");
		page.getParams().put("userid",u.getId());
		Map<String, Object> stateCount=orderService.getStateCount(page);
		request.setAttribute("stateCount", stateCount);
		User user = userService.getUser(u);
		if(user.getPetName() == null){
			String petName =user.getPhone().substring(0, 3)+"****"+user.getPhone().substring(user.getPhone().length()-4, user.getPhone().length());
			user.setPetName(petName);
		}
		String codePre = user.getCodePre();
		String codeSuf = user.getCodeSuf();
		String loginId = user.getId()+"";   
		String vipcode = codePre+loginId+codeSuf;  //定义用户唯一的标识 用于二维码和邀请
		session.setAttribute("vipcode", vipcode);
		request.setAttribute("user", user);
		request.setAttribute("domain", domain);
		view.setViewName("user/personal_center");
		return view;
	}

	@ResponseBody
	@RequestMapping(value = "register")
	public Map<String, Object> register(HttpServletResponse response, HttpServletRequest request,
			@Param("code") String urlCode) {
		this.logBefore(logger, "邀请好友注册");
		Map<String, Object> resMap = new HashMap<String, Object>();
		User uParent = null;
		String friend = request.getParameter("friend");
		String userName = request.getParameter("mobile");
		String pasword = request.getParameter("password");
		String code = request.getParameter("code");
		String hxId = "hltx" + MD5Util.MD5(userName);
		pasword = MD5Util.MD5(pasword);
		if (validateCode(userName, code, "register")) {
			UserLogin login = new UserLogin();
			login.setPwd(pasword);
			login.setUserName(userName);
			login.setHxId(hxId);
			if (friend != null && friend !="") {
				login.setFriend(friend);
				uParent = userVipService.getParentByUserName(friend);
				if (uParent == null) {
					resMap.put("result", this.initResult(ResultInfo.ERROR, "PARENT_NULL", "上级用户不存在", null));
				}else{
					registerMethod(request, resMap, login);
				}
			}else{
				resMap.put("result", this.initResult(ResultInfo.ERROR, "REFERRER_NULL", "推荐人必须填写",null));
			}
		} else {
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expire", MessagesCode.VALIDATE_EORROR));
		}
		this.logAfter(logger);
		return resMap;
	}

	private void registerMethod(HttpServletRequest request, Map<String, Object> resMap, UserLogin login) {
		String msg = validateCocde(request);
		if ("ok".equals(msg)) {
			try {
				int i = userService.findByPhone(login);
				if (i <= 0) {
					int id =userService.saveUserRegister(login);
					if(id > 0){
						userService.saveUserRegister1(login,id);
						User resultUser = userService.getUserInfo(id);
						if (resultUser != null) {
							request.getSession().setAttribute("sessionUser", resultUser);
							resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
						} 
					}else{
						resMap.put("result", this.initResult(ResultInfo.ERROR, "e", "注册繁忙稍后重试!"));
					}
				} else {
					resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "此用户已注册"));
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
		} else if ("expire".equals(msg)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expire", MessagesCode.VALIDATE_EORROR));
		} else {
			resMap.put("result", this.initResult(ResultInfo.ERROR, "error", MessagesCode.VALIDATE_EORROR));
		}
	}

	@ResponseBody
	@RequestMapping("/send")
	public Map<String, Object> send(HttpServletResponse response,HttpServletRequest request){
		this.logBefore(logger, "发送短信验证码");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String mobile = request.getParameter("userName");
		try{
			if(mobile != null){
				logBefore(logger, mobile);
				if(RegexUtils.isMobileNO(mobile)){
					//发送短信
					SmsCodeValidate sms = new SmsCodeValidate();
					sms.setPhone(mobile);
					
					String types =request.getParameter("type");
					sms.setTypes(types);
					SmsCodeValidate validate = smsCodeValidateService.getSmsData(sms);
					if (types != null) {
						Integer is = userService.userIsExists(mobile);
						if("register".equals(types)){
							 if(is > 0){
								 resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.HAVE, "此手机号已被注册"));
							 }else{
								 	if(validate ==null){
								 		sms.setExpireTime("120");
										String code =CustomUtil.buildRandom(6)+"";
										sms.setCode(code);
										sms.setSendNum(0);
										String msg = sendDB(sms, true);
										if (msg == "success") {
											resMap.put("result", this.initResult(ResultInfo.SUCCESS, code, "已发送短信"));
										}
								 	}else{
								 		sms.setExpireTime("60");
										String code =CustomUtil.buildRandom(6)+"";
										sms.setCode(code);
										sms.setSendNum(0);
										String msg = sendDB(sms, false);
										if (msg == "success") {
											resMap.put("result", this.initResult(ResultInfo.SUCCESS, code, "已发送短信"));
										}
								 	}
								 	
							 }
						}else{
							if(is<=0){
								resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "此手机号不存在"));
							}else{
								if (validate ==null) {
									sms.setExpireTime("120");
									String code =CustomUtil.buildRandom(6)+"";
									sms.setCode(code);
									sms.setSendNum(0);
									String msg = sendDB(sms, true);
									if (msg == "success") {
										resMap.put("result", this.initResult(ResultInfo.SUCCESS, code, "已发送短信"));
									}
								}else{
									sms.setTypes(request.getParameter("type"));
									SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); 
									String date = format.format(new Date());
									String date_time= validate.getCreateTime();
									date_time = date_time.substring(0, 10).replace("-", "").trim();
									System.out.println(date+"==="+date_time);
									if(!date.equals(date_time)){
										validate.setSendNum(-1);
										smsCodeValidateService.intiSmsData(validate);
										sms.setExpireTime("120");
										String code =CustomUtil.buildRandom(6)+"";
										sms.setCode(code);
										sms.setSendNum(0);
										String msg = sendDB(sms, false);
										if (msg == "success") {
											resMap.put("result", this.initResult(ResultInfo.SUCCESS, code, "已发送短信"));
										}
									}else{
										if(validate.getSendNum()>=10){
											resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.ERROR, "获取验证码已经达到上线请在次日后再试"));
											//
										}else{
											long  now = System.currentTimeMillis();
											long  dates = Long.valueOf(DateUtil.dateToStamp(validate.getCreateTime())).longValue();
											if(validate != null && validate.getSendNum() < 3){
												sms.setExpireTime("120");
												String code =CustomUtil.buildRandom(6)+"";
												sms.setCode(code);
												sms.setSendNum(0);
												String msg = sendDB(sms, false);
												if (msg == "success") {
													resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "已发送短信"));
												}
											}else{
												if(validate != null &&  validate.getSendNum() >= 3 && ((now/1000) - (dates/1000)) > 900){//发送次数大于3次并且上次生成验证码时间间隔大于15分钟
													sms.setExpireTime("120");
													String code =CustomUtil.buildRandom(6)+"";
													sms.setCode(code);
													sms.setSendNum(0);
													String msg = sendDB(sms, false);
													if (msg == "success") {
														resMap.put("result", this.initResult(ResultInfo.SUCCESS, code, "已发送短信"));
													}
												}else{
													resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.ERROR, "提示网络繁忙/发送验证码过于频繁请在15分钟后再试"));
												}
											}
										}
										
									}
								}
								
							}
							
						}
					}else{
						resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "缺少类型参数"));
					}
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.ERROR, "手机号码不合法!"));
				}
			}else{
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.HPONE_ISNULL, "手机号码不能为空!"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * 验证验证码是否正确
	 * 
	 * @param user
	 * @param response
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "toNewsPwd")
	public Map<String, Object> toNewsPwd(@ModelAttribute User user, HttpServletResponse response,
			HttpServletRequest request) {
		this.logBefore(logger, "设置新密码");
		Map<String, Object> map = new HashMap<>();
		String mobile = request.getParameter("mobile");
		String msg = validateCocde(request);
		if ("ok".equals(msg)) {
			map.put("mobile", mobile);
			map.put("next", "/toNewsPwdPage?mobile=" + mobile);
			map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", MessagesCode.SUCCESS));
		} else if ("expire".equals(msg)) {
			map.put("result", this.initResult(ResultInfo.SUCCESS, "expire", MessagesCode.VALIDATE_EORROR));
		} else {
			map.put("result", this.initResult(ResultInfo.SUCCESS, "error", MessagesCode.VALIDATE_EORROR));
		}
		this.logAfter(logger);
		return map;
	}

	/**
	 * 去向设置新密码页面
	 * 
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toNewsPwdPage")
	public ModelAndView toNewsPwdPage(HttpServletResponse response, HttpServletRequest request) {
		ModelAndView view = this.getModelAndView();
		view.addObject("mobile", request.getParameter("mobile"));
		view.setViewName("user/newpwd");
		return view;

	}

	@ResponseBody
	@RequestMapping(value = "updateNewPwd")
	public Map<String, Object> updateNewPwd(HttpServletResponse response, HttpServletRequest request) {
		this.logBefore(logger, "设置新密码");
		Map<String, Object> map = new HashMap<>();
		String mobile = request.getParameter("userName");
		String password = request.getParameter("password");
		password = MD5Util.MD5(password);
		if (mobile != null) {
			UserLogin login = new UserLogin();
			login.setUserName(mobile);
			login.setPwd(password);
			try {
				userService.updateNewsPwd(login);
				map.put("mobile", mobile);
				map.put("next", "/toLogin");
				map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", MessagesCode.SUCCESS));
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				map.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
		} else {
			map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", MessagesCode.HPONE_ISNULL));
		}
		this.logAfter(logger);
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "updateNewsPwd")
	public Map<String, Object> updatePwd(@ModelAttribute UserLogin login, HttpServletResponse response,
			HttpServletRequest request) {
		this.logBefore(logger, "设置新密码");
		Map<String, Object> map = new HashMap<>();
		if (login != null) {
			try {
				String msg = validateCocde(request);
				if ("ok".equals(msg)) {
					map.put("next", "/toNewsPwd");
					map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", MessagesCode.SUCCESS));
				} else {
					map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", MessagesCode.VALIDATE_EORROR));
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				map.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
		}
		this.logAfter(logger);
		return map;
	}

	private String validateCocde(HttpServletRequest request) {
		String msg = "ok";
		String phone = request.getParameter("mobile");
		String code = request.getParameter("code");
		String types = request.getParameter("type");
		SmsCodeValidate sms = new SmsCodeValidate();
		sms.setPhone(phone);
		sms.setCode(code);
		sms.setTypes(types);
		try {
			SmsCodeValidate validate = smsCodeValidateService.getSmsCode(sms);
			if (validate != null) {
				SmsCodeValidate scv = smsCodeValidateService.getSmsIsExpire(sms);
				if (scv == null) {
					msg = "expire";
				}
			} else {
				msg = "error";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}

	// 验证码验证
	private boolean validateCode(String phone, String code, String types) {
		SmsCodeValidate sv = new SmsCodeValidate();
		sv.setPhone(phone);
		sv.setTypes(types);
		sv.setCode(code);
		long lose = 0;
		try {
			SmsCodeValidate date = smsCodeValidateService.getSmsCode(sv);
			String time = date.getExpireTime();
			if (time != null) {
				lose = Long.parseLong(time);
			}
			Long newTime = System.currentTimeMillis();
			if (lose > (newTime / 1000) && date.getSendNum() < 10) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	private String  sendDB(SmsCodeValidate sms,Boolean o){
		try {
			int i=0;
			if (o) {
				sms.setIsUse("00");
				i= smsCodeValidateService.saveSmsCode(sms);
			}else{
				sms.setIsUse("00");
				i = smsCodeValidateService.updateSmsCode(sms);
			}
			if(i>=1){
				NeteaseSms.sendTemplateSms(sms.getPhone(), sms.getCode());
			}
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			return "error";
		}
}
	
}
